package toDoList.Controllers;

import java.io.*;
import java.util.*;

import com.google.android.maps.GeoPoint;

import toDoList.Manager.DataBaseHelper;
import toDoList.Manager.Logger;
import toDoList.Manager.R;
import toDoList.Manager.R.array;
import toDoList.Manager.R.id;
import toDoList.Manager.R.layout;
import toDoList.Models.CategoryModel;
import toDoList.Models.ToDoItemModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TimePicker;

public class ToDoItemController extends Activity implements ControllerInterface {

	CategoryModel category;
	String realDateTime = "";
	
	/** Runs when the activity first starts */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addtodoitem);
        updateSpinners();
    }
	
	/**
	 * createListener() Ties all of the controllers together
	 */
	public void createListener()
	{
		
	}
	
	/**
	 * updateSpinners() Updates the spinners in the "Create a To Do Item" View
	 */
	public void updateSpinners()
	{
		DataBaseHelper helper = new DataBaseHelper(this);
		//Update the category spinner
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor mCursor = db.query("Category", new String[] {"name", "description", "color"}, null , null, null, null, null);
	    if (mCursor != null) {
		      mCursor.moveToFirst();
	    }
	    
	    //Close the database
	    db.close();
		
	    Spinner catSpinner = (Spinner) findViewById(R.id.categorySpinner);
	    String[] strings = new String[mCursor.getCount()];
	    for(int i = 0; i < strings.length; i++)
	    {
	    	CategoryModel temp = new CategoryModel(mCursor.getString(0), mCursor.getString(1), mCursor.getString(2));
	    	strings[i] = temp.getName();
	    	
	    	if(i < strings.length - 1)
	    		mCursor.moveToNext();
	    }
	    
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, strings);
	    catSpinner.setAdapter(adapter);
	}
	
	/**
	 *  getLatitudeLongitude(String strAddress) Gets the GeoPoint of the address parameter
	 * @param strAddress The address your trying to find coordinates for
	 * @return The geopoint of the address provided
	 */
	public GeoPoint getLatitudeLongitude(String strAddress)
	{
		Geocoder coder = new Geocoder(this);
		List<Address> address;

		try {
		    address = coder.getFromLocationName(strAddress,5);
		    if (address == null) {
		        return null;
		    }
		    Address location = address.get(0);
		    location.getLatitude();
		    location.getLongitude();

		    return new GeoPoint((int) (location.getLatitude() * 1E6),
		                      (int) (location.getLongitude() * 1E6));
		}
		catch(Exception e)
		{
			popUp(e.toString());
		}
		
		return null;
	}
	
	/**
	 * editeDateClicked(View v) Starts the DatePickerController Activity. Allows the user to choose a date and time.
	 * @param v The current view
	 */
	public void editDateClicked(View v)
	{
		Intent i = new Intent(ToDoItemController.this, DatePickerController.class);
		startActivityForResult(i, 1);
	}
	
	/**
	 * okClicked(View v) Runs when the ok button is pressed. Passes back the data for a todoitem.
	 * @param v The current view
	 */
	public void okClicked(View v)
	{
		Intent data = new Intent();
		
		boolean filled = true;
		String errors = "";
		
		if((((EditText)findViewById(R.id.titleText)).getText()).toString() == "")
		{
			errors += "Choose a title";
		}
		if((((EditText)findViewById(R.id.descriptionText)).getText()).toString() == "")
		{
			errors += "Choose a description";
		}
	
		if(filled != true)
		{
			popUp(errors);
		}
		else if(filled == true)
		{
			String title = null;
			String description = null;
			String category = null;
			String location = null;
			
			title = (((EditText)findViewById(R.id.titleText))).getText().toString();
			description = (((EditText)findViewById(R.id.descriptionText))).getText().toString();
			category = ((Spinner)findViewById(R.id.categorySpinner)).getSelectedItem().toString();
			location =  getLatitudeLongitude(((EditText)findViewById(R.id.locationText)).getText().toString()).toString();
		
		    if(title != null)
		    {
		    	data.putExtra("title", title);
		    	Logger.writeLog("The title '" + title + "' was added to the TODOITEM");
		    }
			if(description != null)
			{
				data.putExtra("description", description);
				Logger.writeLog("The description '" + description + "' was added to the TODOITEM");
			}
			if(category != null)
			{
				data.putExtra("category", category);
				Logger.writeLog("The category '" + category + "' was added to the TODOITEM");
			}
			if(location != null)
			{
				data.putExtra("location", location);
				Logger.writeLog("The location '" + location + "' was added to the TODOITEM");
			}
			
			data.putExtra("dateTime", realDateTime);
			Logger.writeLog("The dateTime '" + realDateTime + "' was added to the TODOITEM");
				
			setResult(Activity.RESULT_OK, data);
	        finish();
		}
		else
		{
			popUp(errors);
		}
	}
	
	/**
	 * addCategoryClicked(View v) Start a CategoryController activity. Allows the user to add a new category.
	 * @param v
	 */
	public void addCategoryClicked(View v)
	{
		Intent i = new Intent(ToDoItemController.this, CategoryController.class);
		startActivity(i);
	}
	
	/**
	 * cancelClicked(View view) Cancels this view. Reverts back to the previous view on the stack.
	 * @param view The current view on the screen
	 */
	public void cancelClicked(View v)
	{
		Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        finish();
	}
	
	/**
	 * mapClicked(View v) Unimplemented.
	 * @param v
	 */
	public void mapClicked(View v)
	{
		
	}
	
	/**
	 * onActivityResult(int requestCode, int resultCode, Intent data) Based on the requestCode and resultCode, it will do an activiy after a sub-activity ends
	 * @param requestCode The requestCode passed back by the sub-activity
	 * @param resultCode The resultCode passed back by the sub-activity
	 * @param data The data passed back by the sub-activity
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		switch(requestCode)
		{
			case (1):
			{
				if(resultCode == RESULT_OK)
				{
					String month = data.getStringExtra("month");
					String day = data.getStringExtra("day");
					String year = data.getStringExtra("year");
					String hour = data.getStringExtra("hour");
					String min = data.getStringExtra("min");
					String ampm = "AM";
					realDateTime = year + "-" + day + "-" + month + " " + hour + ":" + min + ":00.000";
					
					if(Integer.parseInt(hour) >= 12)
					{
						ampm = "PM";
						int intHour = Integer.parseInt(hour) % 12;
						hour = String.valueOf(intHour);
					}
					if(hour.equals("0"))
					{
						hour = "12";
					}
					
					String dateTime = month + "/" + day + "/" + year + " " + hour + ":" + min + " " + ampm;
					((EditText)findViewById(R.id.editDateText )).setText(dateTime);
				}
			}
		}
	}

	/**
	 * popUp(String n) Displays a pop-up window with the message "n" inside of it.
	 * @param n The string to display
	 */
	public void popUp(String n) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(n)
		       .setCancelable(false)
		       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		
		builder.show();
	}

}
